<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
 
/**
 * Prunus Cerezo
 *
 * Contenedor Cerezo (tabla)
 *
 * @author		agosto
 * @date		  20090531
 * @version		0.1
 * @copyright	Copyright (c) 2009, 7dedos
 * @link		http://www.7dedos.com.ar
 */
 
 /*
 $this
   ->headers (array de string)
   ->title (string)
   ->data (array)
     ->campos (array de string correspondiente a cada columna definida en headers)
     ->acciones (array de acciones para el campo)
       ->label (string)
       ->uri (string)
       ->js (string)
       ->tip (string)
     ->onclick (array con la accion a procesar si se hace clic en la fila)
       ->uri (string)
       ->js (string)
       ->tip (string)
 */
class prunus_cerezo
{
	protected $ci;
  protected $buffer;
  protected $headers; //array con los titulos de las columnas
  protected $data; //array con los datos de las filas
  protected $offsetPosition;
  protected $actions;
  protected $title;
  protected $helpTrigger;
  protected $lastLineWidth; //usado para trackear el ancho del ultimo bloque abierto
  protected $totalRecords;
  protected $uriSegment;
  public $recordsPerPage;
  protected $offset;
  protected $baseUrl;
    
	public function __construct()	{
		$this->ci =& get_instance();
    $this->ci->load->helper('form');
    $this->ci->load->config('prunus_cerezo');
    $this->offsetPosition = $this->ci->config->item('PRCE_defaultOffset');
    $this->lastLineWidth = 0;
    
		log_message('debug', 'prunus_cerezo inicializado');
	}
	
  private function bufferClear() { $this->buffer = ''; }
  private function bufferAdd($position, $text) { $this->buffer .= $this->ci->prunus_core->gi ( ($this->offsetPosition + $position), $text); }
  
  public function pagination ($total,$baseUrl,$uriSegment=0,$perPage=null) {
    $this->totalRecords = $total;
    $this->baseUrl = $baseUrl;
    if (is_null($perPage)) $perPage = $this->ci->config->item('PRCE_recordsPerPage');
    $this->uriSegment = $uriSegment;
    $this->recordsPerPage = $perPage;
  } //pagination
  
  public function open ($headers, $title = "", $helpTrigger = "",$offset = -1) {
    if ($offset != -1) $this->$offsetPosition = $offset;
    $this->headers = $headers;
    $this->title = $title;
    $this->helpTrigger=$helpTrigger;
  } //open
  
  //actions:
  //  array - [label] texto o id del icono
  //          [uri]   uri de la accion
  //          [js]    javascript de la accion. si viene en blanco uso el uri
  //          [tip]   tooltip para el link
  public function addRecord ($data,$actions,$onclick=null) {
    $this->data[] = array('campos'=>$data,'acciones'=>$actions,'onclick'=>$onclick);
  }
  
  public function addAction ($uri,$text,$onclick='') {
    $this->actions[] = array($uri,$text,$onclick);
  } //addAction
  
  public function render() {
    $this->bufferClear();
    
    $this->bufferAdd(0, "<div class=\"PRCE_container\">");
    
    $hayAccionesEnFilas = FALSE;
    foreach($this->data as $record) if (count($record['acciones']) > 0) $hayAccionesEnFilas = TRUE;
    
    
    if ($this->title != '' || $this->helpTrigger !='') {
      $this->bufferAdd(2, "<div class=\"PRCE_title\">");
      if ($this->title != '') $this->bufferAdd(4, "<span class=\"title\">" . $this->title . "</span>");
      if ($this->helpTrigger != '') $this->bufferAdd(4, $this->helpTrigger);
      $this->bufferAdd(2, "</div>");
    }
    
    $this->bufferAdd(2, "<table class=\"PRCE_table\" summary=\"" . $this->title . "\">");
    $this->bufferAdd(4, "<thead>");
    $this->bufferAdd(6, "<tr>");
    foreach($this->headers as $header) {
      $this->bufferAdd(8, "<th>" . $header . "</th>");
    }
    if ($hayAccionesEnFilas) $this->bufferAdd(8, "<th class=\"PRCE_actions\">" . lang('pr_Actions') . "</th>");
    $this->bufferAdd(6, "</tr>");
    $this->bufferAdd(4, "</thead>");
    $this->bufferAdd(4, "<tbody>");
    if (count($this->data)>0) {
      foreach($this->data as $record) {
        $this->bufferAdd(6, "<tr>");
        foreach($record['campos'] as $field) {
          if ($record['onclick']!==null) {
          
            if (isset($record['onclick']['tip'])) { $tip = $record['onclick']['tip']; } else { $tip = ''; }          
            if (isset($record['onclick']['js'])) {
              //$this->bufferAdd(8, anchor('#',$label,array("onclick"=> $record['onclick']['js'],"title"=>$tip)));
              $this->bufferAdd(8, "<td class=\"PRCE_rowAction\" onclick=\"javascript:" . $record['onclick']['js'] . "\" title=\"" . $tip . "\">" . $field . "</td>");
            } elseif (isset($record['onclick']['uri'])) {
              $this->bufferAdd(8, "<td class=\"PRCE_rowAction\" onclick=\"javascript:window.location='" . $record['onclick']['uri'] . "';\" title=\"" . $tip . "\">" . $field . "</td>");
              //$this->bufferAdd(8, "<td class=\"PRCE_rowAction\">" . anchor($record['onclick']['uri'],$field,array("title"=>$tip)) . "</td>");
              
              //$this->bufferAdd(8, "<td class=\"PRCE_rowAction\" onclick=\"javascript: alert(1);\">" . $field . "</td>");
            }
          
          
          
          
          } else {
            $this->bufferAdd(8, "<td>" . $field . "</td>");
          }
        }
        
        if ($hayAccionesEnFilas) {
          $this->bufferAdd(8, "<td class=\"PRCE_actions\">");
          foreach($record['acciones'] as $action) {
            if (isset($action['tip'])) { $tip = $action['tip']; } else { $tip = ''; }
            if (isset($action['label'])) {
              if (is_numeric($action['label'])) { //es una constante para icono
                switch ($action['label']) {
                  case $this->ci->config->item('PRCE_ico_Delete'): $label = '<span class="PRCE_action PRCE_action_delete">&nbsp;</span>'; break;
                  case $this->ci->config->item('PRCE_ico_Ok'):     $label = '<span class="PRCE_action PRCE_action_ok">&nbsp;</span>';     break;
                  case $this->ci->config->item('PRCE_ico_Edit'):   $label = '<span class="PRCE_action PRCE_action_edit">&nbsp;</span>';   break;
                  case $this->ci->config->item('PRCE_ico_Roles'):  $label = '<span class="PRCE_action PRCE_action_roles">&nbsp;</span>';  break;
                  case $this->ci->config->item('PRCE_ico_Ver'):    $label = '<span class="PRCE_action PRCE_action_ver">&nbsp;</span>';  break;
                  default: 
                    $label = '';
                }
              } else { //es un label de texto
                $label = $action['label'];
              }
              if ($label != '') {
                if (isset($action['js'])) {
                  $this->bufferAdd(8, anchor('#',$label,array("onclick"=> $action['js'],"title"=>$tip)));
                } elseif (isset($action['uri'])) {
                  $this->bufferAdd(8, anchor($action['uri'], $label,array("title"=>$tip)));
                }
              }
            }
          }
          $this->bufferAdd(8, "</td>");
        }
        $this->bufferAdd(6, "</tr>");
      }
    } else {
      $this->bufferAdd(6, "<tr>");
      $this->bufferAdd(8, "<td>" . lang('pr_NoData') . "</td>");
      $this->bufferAdd(6, "</tr>");
    }
    $this->bufferAdd(4, "</tbody>");
    $this->bufferAdd(2, "</table>");


    $this->ci->load->library('pagination');
    $config['base_url'] = $this->baseUrl;
    $config['total_rows'] = $this->totalRecords;
    $config['per_page'] = $this->recordsPerPage;
    $config['num_links'] = 2;
    $config['first_link'] = lang('pr_Primera');
    $config['last_link'] = lang('pr_Ultima');
    $config['num_tag_open'] = '<span class="PRCE_pagination_digit">';
    $config['num_tag_close'] = '</span>';
    $config['cur_tag_open'] = '<span class="PRCE_pagination_digit"><b>';
    $config['cur_tag_close'] = '</b></span>';
    $config['prev_tag_open'] = '<span class="PRCE_pagination_digit">';
    $config['prev_tag_close'] = '</span>';
    $config['next_tag_open'] = '<span class="PRCE_pagination_digit">';
    $config['next_tag_close'] = '</span>';
    $config['first_tag_open'] = '<span class="PRCE_pagination_first">';
    $config['first_tag_close'] = '</span>';
    $config['last_tag_open'] = '<span class="PRCE_pagination_last">';
    $config['last_tag_close'] = '</span>';
    if ($this->uriSegment > 0) $config['uri_segment'] = $this->uriSegment;
    $this->ci->pagination->initialize($config);     
    $this->bufferAdd(2, "<div class=\"PRCE_pagination\">" . $this->ci->pagination->create_links() . "</div>");
    
    if (count($this->actions) > 0) {
      $this->bufferAdd(2, "<h2>" . lang('pr_Actions') . "</h2>");
      $this->bufferAdd(2, "<div id=\"pageActions\">");
      foreach ($this->actions as $action) {
        if ($action[2] == '') {
          $this->bufferAdd(4, "<span class=\"pageAction\">" . anchor($action[0],$action[1]) . "</span>");
        } else {
          $this->bufferAdd(4, "<span class=\"pageAction\">" . anchor('#',$action[1],array("onclick"=> $action[2] )) . "</span>");
        }
      }
      $this->bufferAdd(2, "</div>");
    }

    $this->bufferAdd(0, "</div>");
    
    return $this->buffer;
  } //render
  
}
